/**********************************************************
* @ File name -> led.cpp
* @ Version   -> V1.0
* @ Date      -> 20191029
* @ Brief     -> LED控制相关函数

 V1.*
* @ Revise    ->
**********************************************************/
#include "mod_led.h"

#include "port.h"
#include "platform.h"

#include <string.h>

static void led_all_off() {
	led_off(LED_GREEN);
	led_off(LED_YELLOW);
	led_off(LED_RED);
}

static void led_green_on() {
    led_all_off();
    led_on(LED_GREEN);
}

static void led_yellow_on() {
    led_all_off();
    led_on(LED_YELLOW);
}
static void led_red_on() {
    led_all_off();
    led_on(LED_RED);
}

struct T_Led {
    enum LedMode mode;
    uint32_t cnt;
};

static struct T_Led Led;

static void Led_Show(const struct T_Led *led) {
    switch(led->mode) {
    case LED_MODE_NOMAL:
    case LED_MODE_NETOFFLINE:
         led_green_on();
         break;
    case LED_MODE_WAITGUN:
    case LED_MODE_CHARGE:
         led_yellow_on();
         break;
    case LED_MODE_ALARM:
         led_red_on();
         break;   
    case LED_MODE_NONE:
        led_all_off();
        break;
    default:
        break;
    }
}

static void led_poll(struct T_Led *led) {
    led->cnt++;
    if (!(uint32_t)(led->cnt % 5u)) {
        if (led->mode == LED_MODE_NETOFFLINE) {
            led_toggle(LED_GREEN);
        } else if (led->mode == LED_MODE_WAITGUN) {
            led_toggle(LED_YELLOW);
        }else{
        
        }
        
        led_toggle(LED_SYS);
    }
}

static void led_task(void *pvParameters) {
    pvParameters = pvParameters;
    
    /*lint -e(716) */
    while(1){
        led_poll(&Led);
        os_msleep(100u);
    }
}

void led_set_mode(uint8_t gunid, enum LedMode mode) {
    if (Led.mode != mode) {
        Led.mode = mode;
        Led_Show(&Led);
    }
}

int32_t led_init(void) {
    int32_t ret = 0;
    os_pthread_t led_thread;
    led_port_init();
    memset(&Led, 0, sizeof(Led));
    led_set_mode(0, LED_MODE_NOMAL);
    Led_Show(&Led);
        
    if (os_pthread_create("led", &led_thread, led_task, NULL,  OS_TASK_PRIO_LOW, OS_STACK_SIZE_LITTLE) != 0){
        ret = -1;
    }
    return ret;
}
